<template>
  <div>
    {{ $router.query.type }}
    <upload-excel :before-upload="beforeUpload" :on-success="handleSuccess" />
  </div>
</template>

<script>
import { reqImportEmployee } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    // 上传前校验的方法
    beforeUpload() {
      return true
    //   console.log(111)
    },
    // 上传成功触发的方法
    async handleSuccess({ header, results }) {
      if (this.type === 'user') {
        // 员工
      }
      if (this.type === 'social') {
        // 社保处理
      }
      if (this.type === 'salary') {
        // 工资处理
      }
      //   console.log(header, results)
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
        //   console.log(item[k])
        //   console.log(userRelations[k])
          if (['timeOfEntry', 'correctionTime'].includes(userRelations[k])) {
            obj[englishKey] = this.formatDate(item[k], '-')
          } else {
            obj[englishKey] = item[k]
          }
          const englishKey = userRelations[k]
          obj[englishKey] = item[k]
        //   console.log(obj[englishKey])
        }
        arr.push(obj)
      })
      console.log(arr)
      const { message } = await reqImportEmployee(arr)
      this.$message.success(message)
      //   console.log(res)
      // 返回员工列表
      this.$router.back()
    },
    // 处理excel日期转换
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
